<?php
namespace app\company\controller;

use app\admin\controller\Admin;
use app\common\model\AccountLog;
use app\common\model\BusInquiry;
use app\common\model\BusInquiryDetailSupplier;
use app\common\model\BusInquirySuppliers;
use app\common\model\SalesCompany;
use app\common\model\SysOrder;
use PhpOffice\PhpSpreadsheet\Style\Font;
use think\Exception;

/**
 * 财务管理
 * Class Realdata
 * @package app\gygt\controller
 */
class Order extends Admin
{

    public function getNewInfo()
    {
        $tims = input('times');
        $company_id = input('opt_user_id');
        $times_info = floor($tims / 1000) - 60;
        $param = [
            'add_datetime'=>['>',date('Y-m-d H:i:s',$times_info)],
            'bus_to_company_id'=>$company_id
        ];
        $inquiryModel = new BusInquirySuppliers();
        $num = $inquiryModel->where($param)->count();
        json_return_code($num);
    }
    /**
     * 获取订单列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getList(){
        $page = input('page', 1);
        $limit = input('limit', 20);
        $param = $this->getOrderWhere();
        $model = new BusInquirySuppliers();
        $count = $model->where($param)->count();
        if($page > ceil($count/$limit)){
            $page = ceil($count/$limit);
        }
        $lst = $model->where($param)->order('sure_datetime desc,id desc')->page($page,$limit)->select();

        foreach ($lst as $item){
            $item['tax'] = sprintf('%.2f',($item['freight'] + $item['totall_price'])*$item['tax_rate']/100);
            $item['totall_price_tax'] = sprintf('%.2f',($item['freight'] + $item['totall_price'])*(100+$item['tax_rate'])/100);
            $item['returned_diff'] = sprintf('%.2f',$item['totall_price_tax'] - $item['returned_money']);
        }
        return json_tab_msg($count,$page,$lst,'success');
    }
    /**
     * 列表导出
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function orderExport(){
        $param = $this->getOrderWhere();
        $model = new BusInquirySuppliers();
        $order_lst = $model->where($param)->order('sure_datetime desc,id desc')->select();
        foreach ($order_lst as $item){
            $item['tax'] = round(($item['freight'] + $item['totall_price'])*$item['tax_rate']/100);
            $item['totall_price_tax'] = round($item['freight'] + $item['totall_price'] + $item['tax']);
            $item['returned_diff'] = round($item['totall_price_tax'] - $item['returned_money']);
            $item['returned_money_state'] = $item['returned_money_state']==2?'是':'否';
            $item['invoice'] = $item['invoice_state']==2?$item['invoice_datetime'].'已开':'未开';
            $item['have_returns'] = $item['have_returns']?'有':'无';
        }
        $table_title = ['下单时间', '询价单号', '车牌号', '品牌','车型', '车架号','修理厂名称', '修理厂电话','运费+木架','销售金额', '税点', '含税销售金额','回款金额', '回款时间', '回款差额', '是否结清','发票','有退货'];
        $table_value = ['sure_datetime','bus_inquiry_no','vehicle_license_num','brand_name','car_model','vehicle_frame_no','repair_company_name',
            'repair_company_phone','freight', 'totall_price','tax', 'totall_price_tax', 'returned_money', 'returned_money_datetime',
            'returned_diff','returned_money_state','invoice','have_returns'];
        //导出
        $filename = '销售订单' . date('Ymd');
        export_excle($order_lst, $table_title, $table_value, $filename);
    }
    /**
     * 筛选条件
     * @return array
     */
    private function getOrderWhere(){
        $company_id = input('opt_user_id');
        $due_date = input('due_date','','trim');
        $bus_inquiry_no = input('bus_inquiry_no','','trim');
        $car_model = input('car_model','','trim');
        $vehicle_frame_no = input('vehicle_frame_no','','trim');
        $vehicle_license_num = input('vehicle_license_num','','trim');
        $brand_name = input('brand_name','','trim');
        $repair_company = input('repair_company','','trim');
        $param = [
            'bus_to_company_id'=>$company_id,
            'state'=>6
        ];
        if($due_date){
            $date_arr = explode(' - ',$due_date);
            if(!empty($date_arr)){
                $param['sure_datetime'] = ['between', [trim($date_arr[0]), date('Y-m-d', strtotime ("+1 day", strtotime(trim($date_arr[1]))))]];
            }
        }

        if($bus_inquiry_no){
            $param['bus_inquiry_no'] = ['like','%'.$bus_inquiry_no.'%'];
        }
        if($car_model){
            $param['car_model'] = ['like','%'.$car_model.'%'];
        }
        if($vehicle_frame_no){
            $param['vehicle_frame_no'] = ['like','%'.$vehicle_frame_no.'%'];
        }
        if($vehicle_license_num){
            $param['vehicle_license_num'] = ['like','%'.$vehicle_license_num.'%'];
        }
        if($brand_name){
            $param['brand_name'] = ['like','%'.$brand_name.'%'];
        }
        if($repair_company){
            $param['repair_company_name|repair_company_phone'] = ['like','%'.$repair_company.'%'];
        }
        return $param;
    }

    /**
     * 获取首页统计数据
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOrderSum(){
        $company_id = input('opt_user_id');
        $order_model = new BusInquirySuppliers();
        $paramY['bus_to_company_id'] = $company_id;
        $paramY['add_datetime'] = ['>=',date('Y-01-01 00:00:00')];
        // 本年全部新增询价
        $pagobj['year_inquiry_num'] = $order_model->where($paramY)->count();
        $paramY['state'] = 6;
        $paramY['sure_datetime'] = ['>=',date('Y-01-01 00:00:00')];
        $pagobj['year_order_num'] = $order_model->where($paramY)->count();
        $year_purchase_info = $order_model->field('sum((totall_price+freight)*(100+tax_rate)/100) as total_cost,sum(returned_money) as pay_cost')->where($paramY)->find();
        $pagobj['year_purchase_total_cost'] = sprintf('%.2f',$year_purchase_info['total_cost']);
        $pagobj['year_purchase_pay_cost'] = sprintf('%.2f',$year_purchase_info['pay_cost']);
        // 本月
        $time_start2 = date("Y-m-01", time()).' 00:00:00';
        $time_end2 =  date('Y-m-t', time()).' 23:59:59';
        $paramM['bus_to_company_id'] = $company_id;
        $paramM['add_datetime'] = ['between', [$time_start2, $time_end2]];
        $pagobj['month_inquiry_num'] = $order_model->where($paramM)->count();
        $paramM['sure_datetime'] = ['between', [$time_start2, $time_end2]];
        $paramM['state'] = 6;
        $pagobj['month_order_num'] = $order_model->where($paramM)->count();
        $month_purchase_info = $order_model->field('sum((totall_price+freight)*(100+tax_rate)/100) as total_cost,sum(returned_money) as pay_cost')->where($paramM)->find();
        $pagobj['month_purchase_total_cost'] = sprintf('%.2f',$month_purchase_info['total_cost']);
        $pagobj['month_purchase_pay_cost'] = sprintf('%.2f',$month_purchase_info['pay_cost']);
        // 今日新增
        $date = date("Y-m-d");
        $time_start3 = $date.' 00:00:00';
        $time_end3 = $date.' 23:59:59';
        $paramD['state'] = ['<',2];
        $paramD['bus_to_company_id'] = $company_id;
        $pagobj['today_inquiry_num'] = $order_model->where($paramD)->count();
        $paramD['state'] = 2;
        $pagobj['today_bid_num'] = $order_model->where($paramD)->count();
        $detailModel = new BusInquiryDetailSupplier();
        $pagobj['today_return_num'] = $detailModel->where(['returns_datetime'=>['between', [$time_start3, $time_end3]],'state'=>4,'add_company_id'=>$company_id])->count();
        $accountLogModel = new AccountLog();
        $pagobj['today_returned_money'] = $accountLogModel->where(['pay_datetime'=>['between', [$time_start3, $time_end3]],'company_type'=>2,'company_id'=>$company_id])->sum('account');;
        json_return_code($pagobj);
    }


    public function getHistogram()
    {
        $company_id = input('opt_user_id');
        $type = input('type',0); // 0本周  1 本月
        $now = time();
        $end_time = date('Y-m-d', $now).' 00:00:00';
        $times = [];
        if($type == 1){
            for($i=29;$i>=0;$i--) {
                $times[] = date('m-d', strtotime('-' . $i . ' day', $now));
            }
            $start_time = date('Y-m-d', strtotime('-29 day', $now)).' 00:00:00';
        }else{
            for($i=7;$i>0;$i--) {
                $times[] = date('m-d', strtotime('-' . $i . ' day', $now));
            }
            $start_time = date('Y-m-d', strtotime('-7 day', $now)).' 00:00:00';
        }

        $param = [
            'pay_datetime'=>['between', [$start_time, $end_time]],
            'company_id'=>$company_id,
            'company_type'=>2,
        ];
        $order_model = new AccountLog();
        $order_lst = $order_model->where($param)->order('pay_datetime asc')->select();
        $arr = [];
        foreach ($times as $item){
            $list = [
                'add_date'=>$item,
                'order_return'=>0,
            ];
            foreach ($order_lst as $key=>$order){
                if($item == date('m-d', strtotime($order['pay_datetime']))){
                    $list['order_return'] = round($list['order_return'] + $order['account'], 2);
                    unset($order_lst[$key]);
                }
            }
            $arr[] = $list;
        }
        $histogram = [
            'xdata' => $times,
            'order_return' => array_column($arr, 'order_return'),
        ];
        json_return_code($histogram);
    }
}
